#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>

/*
 *  线程的同步：要求reversMsg函数在printfMsg函数前执行
 *  1.基于Posix无名信号灯，两个信号灯
reversMsg--------
printfMsg--------
buf : 987654321
reversMsg--------
printfMsg--------
buf : 123456789
reversMsg--------
printfMsg--------
buf : 987654321

*/

#define N 64

typedef struct message {
	char buf[N];
	int len;
}msg_t;

sem_t semRev;
sem_t semPrn;

void * reverseMsg(void *);
void * printfMsg(void *);

int main(int argc, char * argv[]){
	msg_t msg = {"123456789", 9};
	pthread_t tid[2];

	//初始值为1，则先执行
	sem_init(&semRev, 0, 1);
	//初始值为0，则后执行
	sem_init(&semPrn, 0, 0);

	pthread_create(&tid[0], NULL, reverseMsg, (void *)&msg);
	pthread_create(&tid[1], NULL, printfMsg, (void *)&msg);
	
	pthread_join(tid[0], NULL);
	pthread_join(tid[1], NULL);

	return 0;
}

//反转字符串
void * reverseMsg(void * arg){
	msg_t * msg = (msg_t *)arg;
	int i = 0;
	char tmpChar;

	while(1){
		sem_wait(&semRev);
		printf("reversMsg--------\n");
		for(i = 0 ; i < msg->len / 2 ; i++){
			tmpChar = msg->buf[i];
			msg->buf[i] = msg->buf[msg->len - i - 1];
			msg->buf[msg->len - i - 1] = tmpChar;
		}
		sem_post(&semPrn);
	}
	return NULL;
}

//打印字符串
void * printfMsg(void * arg){
	msg_t * msg = (msg_t *)arg;
	while(1){
		sem_wait(&semPrn);
		printf("printfMsg--------\n");
		printf("buf : %s\n", msg->buf);
		sem_post(&semRev);
		sleep(1);
	}

	return NULL;
}
